package com.example.demo.core.handlerMapping;


import cn.hutool.cache.Cache;
import com.example.demo.core.annotation.Mapping;
import com.example.demo.core.handlerMapping.handler.Handler;
import com.example.demo.core.handlerMapping.handler.SimpleHandler;
import com.example.demo.core.handlerMapping.interfaces.HandlerMapping;
import com.example.demo.core.util.XmlUtil;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import javax.sip.RequestEvent;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.example.demo.core.handlerMapping.interfaces.GB28181.*;

/**
 * 消息处理映射
 * @author yezhihao
 * https://gitee.com/yezhihao/jt808-server
 */
public abstract class AbstractHandlerMapping implements HandlerMapping {


    private final Map<Object, Handler> handlerMap = new HashMap<>(64);
    /**
     * 将Endpoint中被@Mapping标记的方法注册到映射表
     */
    protected synchronized void registerHandlers(Object bean) {
        Class<?> beanClass = bean.getClass();
        Method[] methods = beanClass.getDeclaredMethods();
        for (Method method : methods) {
            Mapping mapping = method.getAnnotation(Mapping.class);
            if (mapping != null) {
                String desc = mapping.desc();
                String[] types = mapping.types();
                Handler handler = new SimpleHandler(bean, method, desc);
                for (String type : types) {
                    handlerMap.put(type, handler);
                }
            }
        }
    }


    @Override
    public String getMessageType(RequestEvent requestEvent) throws DocumentException {
        String methodType = requestEvent.getRequest().getMethod();
        switch (methodType){
            case 注册:{
                methodType= 注册;
                break;
            }
            case 消息: {
                Element rootElement = XmlUtil.getRootElement(requestEvent, null);
                String cmdType = rootElement.element("CmdType").getTextTrim();
                if (cmdType.equals(心跳)){
                    methodType= 心跳;
                }else if (cmdType.equals(查询目录)){
                    methodType= 查询目录;
                }
                break;
            }
            default:{

            }

        }
        return methodType;
    }

    /**
     * 根据消息类型获取Handler
     */
    @Override
    public Handler getHandler(String messageType) {
        return handlerMap.get(messageType);
    }
}